package de.playmee.tasks;

import java.util.List;

import de.playmee.Weather;
import de.playmee.Weather.Condition;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;

public class UpdateWeatherConditionsTask extends AsyncTask<Void, Void, Void> {
	
	private final String TAG = "UpdateWeatherConditionsTask";
	
	private Location location;
	private Weather weather;
	private List<WeatherUpdatedListener> listeners;
	
	public UpdateWeatherConditionsTask(Location location, Weather weather,
			List<WeatherUpdatedListener> listeners) {
		this.location = location;
		this.weather = weather;
		this.listeners = listeners;
	}

	@Override
	protected Void doInBackground(Void... params) {
		Log.i(TAG, weather.getCurrentWeather()+"");
		// update with last known location
		if (location == null) {
			if (weather.getCurrentWeather() != null)
				weather.update();
		}
		
		// update with new location
		else {
			int x = (int) (location.getLatitude() * 1E6);
			int y = (int) (location.getLongitude() * 1E6);
			weather.update(x, y);
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		Condition currentWeahter = weather.getCurrentWeather();
		if (currentWeahter != null) {
			// notify all listeners
			for (WeatherUpdatedListener listener : listeners) {
				listener.onWeatherUpdated(currentWeahter);
			}
		}
	}
	
	public interface WeatherUpdatedListener {
		public void onWeatherUpdated(Condition condition);
	}
}
